package cn.mw.cmdb.template.strategy.handler;

import cn.mw.cmdb.entity.InstanceInfoExtend;
import cn.mw.cmdb.entity.sanxia.FileInfo;
import cn.mw.cmdb.exception.ZabbixResultException;
import cn.mw.cmdb.service.AssetsManageService;
import cn.mw.cmdb.template.constant.MwTemplateConfigurationConstant;
import cn.mw.cmdb.template.entity.MonitorItemDto;
import cn.mw.cmdb.template.entity.TriggerDto;
import cn.mw.cmdb.template.entity.convert.MwMonitorItemConvertDto;
import cn.mw.cmdb.template.entity.convert.MwTemplateConvertOne;
import cn.mw.cmdb.template.entity.convert.MwTriggerConvertDto;
import cn.mw.cmdb.template.enums.TemplateDetailEnum;
import cn.mw.cmdb.template.param.MonitorItemParam;
import cn.mw.cmdb.template.param.MwTemplateConfigurationParam;
import cn.mw.cmdb.template.strategy.TemplateDetailHandler;
import cn.mw.cmdb.template.utils.TemplateSortUtil;
import cn.mw.cmdb.util.FilePost;
import cn.mw.microMonitorCommon.constants.ZabbixApiConstants;
import cn.mw.microMonitorCommon.constants.ZabbixMethodConstants;
import cn.mw.microMonitorCommon.entity.autops.AutopsReferencingScript;
import cn.mw.microMonitorCommon.entity.autops.AutopsReferencingScriptVariable;
import cn.mw.microMonitorCommon.entity.zabbix.MWZabbixAPIResult;
import cn.mw.microMonitorCommon.util.ListMapObjUtils;
import cn.mw.microMonitorCommon.util.SpringUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static cn.mw.cmdb.util.ValConvertUtil.strValueConvert;

/**
 * @description 监控项处理
 */
@Service
@Slf4j
public class MonitorItemHandler extends TemplateDetailHandler {

    private final String VALUE_TYPE = "value_type";
    private final String units = "units";
    private final String VALUE_MAP_ID = "valuemapid";


    @Override
    public TemplateDetailEnum handlerType() {
        return TemplateDetailEnum.MONITOR_ITEM;
    }


    @Override
    public Object getData(MwTemplateConfigurationParam param) {
        List<MonitorItemDto> monitorItemDtos = new ArrayList<>();
        Map zabbixTemplateParam = new HashMap();
        if(StringUtils.isNotEmpty(param.getTemplateId())){
            zabbixTemplateParam.put(MwTemplateConfigurationConstant.TEMPLATE_IDS,param.getTemplateId());
        }
        if(StringUtils.isNotEmpty(param.getHostId())){
            zabbixTemplateParam.put(HOST_IDS,param.getHostId());
        }
        zabbixTemplateParam.put(MwTemplateConfigurationConstant.OUTPUT,MwTemplateConfigurationConstant.EXTEND);
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.ITEM_GET, zabbixTemplateParam);
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        List<MwMonitorItemConvertDto> items = JSONArray.parseArray(String.valueOf(zabbixAPIResult.getData()), MwMonitorItemConvertDto.class);
        if(CollectionUtils.isEmpty(items)){return monitorItemDtos;}
        if(CollectionUtils.isEmpty(items)){return monitorItemDtos;}
        for (MwMonitorItemConvertDto item : items) {
            MonitorItemDto itemDto = new MonitorItemDto();
            itemDto.extractFrom(item);
            monitorItemDtos.add(itemDto);
        }
        //获取监控项的触发器信息
        List<String> itemIds = monitorItemDtos.stream().map(s -> s.getItemId()).collect(Collectors.toList());
        Map zabbixTriggerParam = new HashMap();
        zabbixTriggerParam.put(MwTemplateConfigurationConstant.OUTPUT,Arrays.asList(TRIGGER_ID,description,expression,priority,status));
        zabbixTriggerParam.put(MwTemplateConfigurationConstant.ITEM_IDS,itemIds);
        zabbixTriggerParam.put(MwTemplateConfigurationConstant.selectItems,Arrays.asList(MwTemplateConfigurationConstant.ITEM_ID,MwTemplateConfigurationConstant.NAME));
        MWZabbixAPIResult triggerResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.TRIGGER_GET, zabbixTriggerParam);
        if(triggerResult == null || triggerResult.isFail()){
            throw new ZabbixResultException(String.valueOf(triggerResult.getData()));
        }
        List<MwTriggerConvertDto> triggerConvertDtos = JSONArray.parseArray(String.valueOf(triggerResult.getData()), MwTriggerConvertDto.class);
        if(CollectionUtils.isEmpty(triggerConvertDtos)){
            if(CollectionUtils.isNotEmpty(monitorItemDtos) && StringUtils.isNotEmpty(param.getDetailName())){
                monitorItemDtos = monitorItemDtos.stream().filter(item->item.getName().contains(param.getDetailName())).collect(Collectors.toList());
            }
            //数据排序
            List realData = TemplateSortUtil.templateSortList(monitorItemDtos,param,param.getQuery());
            if(param.getPageNum() == null || param.getPageSize() == null){
                return realData;
            }
            Page page = pageHandler(realData, param.getPageNum(), param.getPageSize());
            return page;
        }
        List<TriggerDto> triggerDtos = new ArrayList<>();
        for (MwTriggerConvertDto triggerConvertDto : triggerConvertDtos) {
            List<MwMonitorItemConvertDto> itemConvertDtos = triggerConvertDto.getItems();
            if(CollectionUtils.isEmpty(itemConvertDtos)){continue;}
            for (MwMonitorItemConvertDto itemConvertDto : itemConvertDtos) {
                TriggerDto triggerDto = new TriggerDto();
                triggerDto.extractFrom(triggerConvertDto);
                triggerDto.setItemId(itemConvertDto.getItemid());
                triggerDtos.add(triggerDto);
            }
        }
        if(CollectionUtils.isEmpty(triggerDtos)){return monitorItemDtos;}
        Map<String, List<TriggerDto>> triggerMap = triggerDtos.stream().collect(Collectors.groupingBy(item -> item.getItemId()));
        for (MonitorItemDto monitorItemDto : monitorItemDtos) {
            List<TriggerDto> dtos = triggerMap.get(monitorItemDto.getItemId());
            monitorItemDto.setTriggers(dtos);
        }
        if(CollectionUtils.isNotEmpty(monitorItemDtos) && StringUtils.isNotEmpty(param.getDetailName())){
            monitorItemDtos = monitorItemDtos.stream().filter(item->item.getName().contains(param.getDetailName())).collect(Collectors.toList());
        }
        //数据排序
        List realData = TemplateSortUtil.templateSortList(monitorItemDtos,param,param.getQuery());
        if(param.getPageNum() == null || param.getPageSize() == null){
            return realData;
        }
        Page page = pageHandler(realData, param.getPageNum(), param.getPageSize());
        return page;
    }

    @Override
    public Object createData(MwTemplateConfigurationParam param) {
        Object detailData = param.getDetailData();
        MonitorItemParam monitorItemParam = JSONObject.parseObject(JSONObject.toJSONString(detailData), MonitorItemParam.class);
        tagHandler(monitorItemParam);
        Map zabbixParam = ListMapObjUtils.beanToMap(monitorItemParam);
        delMapNullValue(zabbixParam);
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.ITEM_CREATE, zabbixParam);
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        sendFile(monitorItemParam);
        return null;
    }

    /**
     * 分发操作-lumingming
     * @param monitorItemParam
     */
    private void sendFile(MonitorItemParam monitorItemParam)  {
        if (open){
            String key = monitorItemParam.getKey_();//脚本键值
            //查询模板下的主机
            String hostId = monitorItemParam.getHostid();
            Map map = new HashMap();
            map.put("mw_hostTemplateId",hostId);
            //获取监控项对应的资产
            //挑起分发数据
            List<InstanceInfoExtend> m = null;
            try {
                AssetsManageService assetsManageService = SpringUtils.getBean(AssetsManageService.class);
                m = assetsManageService.doSelectInstanceList(map);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            List<String> ip = new ArrayList<>();
            m.forEach(e->ip.add(e.getInBandIp()));
            if (ip.size()>0){
                //获取脚本，分发
                AutopsReferencingScript autopsReferencingScript = opsengineApi.SelectZabbixAutopsScript(key);
               if (autopsReferencingScript!=null){
                   String name = UUID.randomUUID()+opsengineApi.SelectZabbixAutopsScriptType(autopsReferencingScript.getAutopsScriptTypeId());
                   String configName = UUID.randomUUID()+".config";
                   FileInfo jsonObject = new FileInfo();
                   try {
                       log.info("开始上传");
                       log.info(autopsReferencingScript.getAutopsReferencingScriptContent()+"."+name
                               +"."+ url+"."+menuId+"."+accountId+"."+userid+"."+fileType);
                       jsonObject = FilePost.uploadFile(autopsReferencingScript.getAutopsReferencingScriptContent()
                               ,name,url,menuId,accountId,userid,fileType);
                       log.info(jsonObject.toString());
                       JSONObject jsonObject1 = FilePost.sendFile(workflowId,sendUrl,accountId,userid,workOrderId,destinationPath,ip,List.of(jsonObject));
                       jsonObject = FilePost.uploadFile(FilePost.content(autopsReferencingScript.getAutopsReferencingScriptVariableList(),destinationPath)
                               ,configName,url,menuId,accountId,userid,fileType);
                       JSONObject jsonObject2 = FilePost.sendFile(workflowId,sendUrl,accountId,userid,workOrderId,destinationPath,ip,List.of(jsonObject));
                   } catch (IOException e) {
                       throw new RuntimeException(e);
                   }
               }
            }
        }
    }




    private void tagHandler(MonitorItemParam monitorItemParam) {
        List<Map> tags = monitorItemParam.getTags();
        if(CollectionUtils.isEmpty(tags)){return;}
        List<String> applications = new ArrayList<>();
        for (Map tag : tags) {
            if(tag.containsKey(applicationId)){
                applications.add(tag.get(applicationId).toString());
            }
        }
        monitorItemParam.setApplications(applications);
    }

    @Override
    public Object updateData(MwTemplateConfigurationParam param) {
        Object detailData = param.getDetailData();
        MonitorItemParam monitorItemParam = JSONObject.parseObject(JSONObject.toJSONString(detailData), MonitorItemParam.class);
        tagHandler(monitorItemParam);
        Map zabbixParam = ListMapObjUtils.beanToMap(monitorItemParam);
        delMapNullValue(zabbixParam);
//        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.ITEM_UPDATE, zabbixParam);
//        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
//            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
//        }
        sendFile(monitorItemParam);
        return null;
    }

    @Override
    public Object deleteData(MwTemplateConfigurationParam param) {
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.ITEM_DELETE, param.getDetailDeleteIds());
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        return null;
    }

    @Override
    public Object selectDataById(MwTemplateConfigurationParam param) {
        //根据监控项ID查询数据
        Map zabbixParam = new HashMap();
        zabbixParam.put(MwTemplateConfigurationConstant.ITEM_IDS,Arrays.asList(param.getDetailId()));
        zabbixParam.put(MwTemplateConfigurationConstant.OUTPUT,MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectTags,MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectApplications,MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectPreprocessing,MwTemplateConfigurationConstant.EXTEND);
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.ITEM_GET, zabbixParam);
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(strValueConvert(zabbixAPIResult.getData()));
        }
        List<MonitorItemParam> monitorItemParams = JSONArray.parseArray(JSON.toJSONString(zabbixAPIResult.getData()), MonitorItemParam.class);
        if(CollectionUtils.isEmpty(monitorItemParams)){return null;}
        return monitorItemParams.get(0);
    }
}
